package com.company.gas.config;

import com.company.gas.pojo.SystemUser;
import com.company.gas.service.ISystemUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * @author: Li Guangdi
 *
 */

public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("这里实现授权功能");
        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        /*//添加资源的授权字符串
        //info.addStringPermission("facility:add");  //硬编码（测试用） 连接数据库之后不使用*/

        //到数据库查询当前登录用户的授权字符串
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        SystemUser systemUser =(SystemUser)subject.getPrincipal();
        SystemUser dbUser = userService.querySystemUserByID(systemUser.getUserId());

        info.addStringPermission(dbUser.getPrivilege());
        return info;
    }

    @Autowired
    private ISystemUserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        System.out.println("这里实现认证功能");
        //编写shiro判断逻辑，判断用户名和密码
        //1.判断用户名
        UsernamePasswordToken token = (UsernamePasswordToken)arg0;
        SystemUser systemUser = userService.querySystemUserByID(token.getUsername());
        if (systemUser==null){
            //用户名不存在
            return null;//shiro底层抛出UnKnowAccountException
        }
        //2.判断密码
        return new SimpleAuthenticationInfo(systemUser,systemUser.getPassword(),"");

    }
}
